<style scoped>
.outer{width: 100%;height: 100%;position: relative;padding: 10px;background: #fff;border-radius: 8px;}

.el-tabs{width: 300px;height: 100%;overflow: hidden;}
.el-tab-pane>div{overflow:auto;}
.el-tab-pane>div::-webkit-scrollbar{display: none;}

.type_map>div{display: flex;flex-wrap: wrap;padding: 05px;user-select: none;}
.type_map>div .title{width: 100%;padding: 20px 0 05px 0;}
.type_map>div .row{width: 80px;height: 80px;margin: 05px;font-size: 14px;text-align: center;border-radius: 05px;cursor: pointer;transition: transform 0.4s;flex-direction: column;justify-content: center;align-items: center;}
.type_map>div .row img{width: 40px;}
.type_map>div .row:hover{box-shadow: 0 0 02px 02px var(--ok);}
.link_list{padding: 0 10px;}
.link_list>div{padding: 10px 0;font-size: 14px;}
.link_list .title{justify-content: space-between;}
.link_list .title b{color: var(--ok);font-size: 20px;}
.link_list .title span{cursor: pointer;}

.phone-outer{box-sizing: border-box;width: 360px;height: 100%;border: 10px solid #000;border-radius: 20px;overflow: hidden;}
.phone-content{position: relative;font-size: 12px;width: 100%;overflow: auto;background-color: var(--bg);}
.phone-content::-webkit-scrollbar{display: none;}
.phone-content>.card_list{width: 100%;min-height: 100%;}
.phone-content .card_row{position: relative;width: 100%;margin: 10px 0;border: 1px solid var(--bg);user-select: none;}
.phone-content .card_row .disabled{position: absolute;left: 0;top: 0;width: 100%;height: 100%;background: var(--fail);opacity: 0.5;}
.phone-content .card_row:hover{border-color: var(--el-color-primary-light-3);}
.phone-content .card_row:before{position: absolute;left: 0;display: none;content: '-----------------插入板块-----------------';font-size:09px;line-height: 1;color: var(--fail);text-align: center;width: 100%;}
.phone-content .card_row.add_before:before{display: block;top: -10px;}
.phone-content .card_row.add_after:before{display: block;bottom: -10px;}

.phone-content .footer{position: sticky;width: 100%;z-index: 9;bottom: 0;left: 0;background: #fff;border-top: 1px solid #eee;overflow: hidden;}
.phone-content .footer .inner{width: 100%;justify-content: space-between;}
.phone-content .footer .inner>.footer_row{font-size: 12px;text-align: center;}
.phone-content .footer .inner>.footer_row i{font-size: 22px !important;}

</style>
<template>
  <div class="flex outer">

    <el-tabs :stretch="true">
      <el-tab-pane name="0" label="组件选择">
        <div class="type_map">
          <div class="group" v-for="row in type_map">
            <p class="title">{{row.content}}</p>
            <div class="row flex" v-for="v in row.children" draggable="true" @dragstart="dragstart({type:v.value})" @dragend="dragend">
              <img :src="v.img_path" draggable="false">
              <p class="text-ellipsis" :title="v.content">{{v.content}}</p>
            </div>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane name="1" label="页面链接">
        <div class="link_list">
          <textarea ref="input_copy" style="position: fixed;left: 200%;top: 200%;"></textarea>
          <div v-for="row in link_list">
            <p class="title flex"><b>{{row.title}}</b> <span @click="copy(row.url)">复制</span></p>
            <p><span style="white-space: nowrap;">地址：</span>{{row.url}}</p>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <div class="phone-outer flex" style="flex-direction: column;">
      <img src="@/assets/img/phone-head.png" style="width: 100%;">
      <div class="phone-content max">
        <div class="card_list" @dragover.prevent="dragover($event)" @drop="drop($event)">
          <template v-for="(row,i) in card_list">
            <el-popover trigger="hover" placement="right" :width="60">
              <template #reference>
                <div class="card_row" :class="{add_before:i==drop_index&&drop_dt_index==0, add_after:i==drop_index&&drop_dt_index==1}" :index="i" draggable="true" @dragstart="dragstart({index:i})" @dragend="dragend">
                  <component :is="'type_'+row.type" v-bind="row" v-if="row.list.length"></component>
                  <h1 v-else style="text-align: center;color: var(--fail);">项目内容为空，前端不会显示</h1>
                  <div class="disabled" v-if="row.status==0"></div>
                </div>
              </template>
              <div class="flex">
                <el-button @click.stop="to_edit(row)" circle type="primary"><i ico="s94" class="ico-edit"></i></el-button>
                <el-button @click.stop="del(i)" circle type="danger"><i ico="s94" class="ico-delete"></i></el-button>
              </div>
            </el-popover>
          </template>
        </div>
        <div class="footer" v-if="footer.length">
          <el-popover trigger="hover" placement="right" :width="60">
            <template #reference>
              <div class="inner flex">
                <div class="footer_row" v-for="row in footer">
                  <iconfont :value="row.icon" :is_info="true"></iconfont>
                  <p>{{row.title}}</p>
                </div>
              </div>
            </template>
            <div class="flex">
              <el-button v-if="in_right('Config/edit_value')" @click.stop="iframe('/config/edit_value?key=home.bottom_link')" circle type="primary"><i ico="s94" class="ico-edit"></i></el-button>
            </div>
          </el-popover>
        </div>
      </div>
    </div>

  </div>

  <el-dialog v-model="show_edit" :width="'80%'" :draggable="true" style="height: 90vh;margin: 5vh auto;">
    <forms ref="forms" :config="config" @submit:forms="onsubmit">
    </forms>
  </el-dialog>

</template>
<script>
import type_0 from "@/components/index_card/type_0.vue";
import type_1 from "@/components/index_card/type_1.vue";
import type_2 from "@/components/index_card/type_2.vue";
import type_3 from "@/components/index_card/type_3.vue";
import type_4 from "@/components/index_card/type_4.vue";
import type_5 from "@/components/index_card/type_5.vue";
import type_6 from "@/components/index_card/type_6.vue";
import type_7 from "@/components/index_card/type_7.vue";
import type_8 from "@/components/index_card/type_8.vue";
export default {
  props: ['__iframe'],
  components: {type_0, type_1, type_2, type_3, type_4, type_5, type_6, type_7, type_8},
  data(){
    let app = this, btns = {}, is_del = this.$get('is_del');

    let type_map = [], group_name_cache = [];
    this.admin_config('status_alias_map.index_card.type').forEach(function (v,type){
      let arr = v.split('-');
      let index = group_name_cache.indexOf(arr[0]);
      let row = {content:arr[1], value:type, img_path: app.assets_path(`/img/index_card/type${type}.png`)}
      if (index === -1){
        group_name_cache.push(arr[0]);
        type_map.push({content: arr[0], value:arr[0], children:[row]})
      }else {
        type_map[index].children.push(row);
      }
    })

    let link_list = [
      {title:'首页',url:'/'},
      {title:'文章列表',url:'/pages/newsLsit/newsLsit'},
      {title:'文章详情',url:'/pages/newsDetails/newsDetails?id=文章ID'},
      {title:'商品列表',url:'/pages/shop/shop?title=页面标题'},
      {title:'商品详情',url:'/pages/goodsDetails/goodsDetails?id=商品ID'},
      {title:'课程列表',url:'/pages/course/course'},
      {title:'课程详情',url:'/pages/classDetails/classDetails?id=课程ID'},
      {title:'活动详情',url:'/pages/activityDetails/activityDetails?id=活动ID'},
      {title:'海报分享',url:'/pages/posterList/posterList?title=页面标题&label=标签名1,标签名2'},
      {title:'海报分享记录',url:'/pages/visitor/visitor?title=页面标题'},
      {title:'购物车',url:'/pages/shopCart/shopCart'},
      {title:'我的',url:'/pages/my/my'},
      {title:'会员中心',url:'/pages/vipCore/vipCore?title=页面标题'},
      {title:'用户余额',url:'/pages/myMoney/myMoney?title=页面标题'},
      {title:'团队管理',url:'/pages/extension/extension?title=页面标题'},
      {title:'收货地址管理',url:'/pages/address/address?title=页面标题'},
      {title:'代理商申请',url:'/pages/empowerList/empowerList?title=页面标题'},
      {title:'代理商申请记录',url:'/pages/submitRecord/submitRecord?title=页面标题'},
      {title:'代理商分布',url:'/pages/argentMap/argentMap?title=页面标题'},
      {title:'我的课程',url:'/pages/myClass/myClass?index=0'},
      {title:'课程收藏',url:'/pages/myClass/myClass?index=1'},
      {title:'赠送课程',url:'/pages/giveLessonList/giveLessonList'},
    ];

    let forms_config = {
      title: {label:'板块标题',name:'title',type:'text_one',tips:'',validate:['nullable','max:120']},
      type: {label:'板块类型',name:'type',type:'select_one',config:type_map,tips:'选择板块类型',value:'',validate:['required']},
      config: {label:'配置',name:'config',type:'json_param',config:[],tips:'',validate:['json']},
      model_name: {label:'数据模型',name:'model_name',type:'select_one',config:[],tips:'选择板块内容的模型',value:'',validate:['required']},
      object_ids: {label:'项目id集',name:'object_ids',type:'list_ids',config:'',tips:'选择板块内容的ID集',validate:['required']},
      href: {label:'跳转链接',name:'href',type:'text_one',tips:'',validate:['nullable', 'max:255']},
      status: {label:'状态',name:'status',type:'radio_switch',config:['禁用','启用'],tips:'',value:1},
    }

    return {
      type_map: type_map,
      link_list: link_list,

      card_list: [],
      footer: [],
      list_id_config_map: {
        'agent': 'agent/index',
      },

      config: forms_config,
      show_edit: false,
      edit_row: {},
      drag_row: false,
      drop_index: -1,
      drop_dt_index: 0,
    }
  },
  methods: {
    to_edit(row){
      this.show_edit = true;
      this.edit_row = row;
      setTimeout(()=>{
        this.$refs['forms'].init(row);
      },20)
    },
    del(i){
      this.confirm('是否确定删除此板块', ()=>{
        this.card_list.splice(i,1);
      })
    },
    get_list(model_name, ids){
      return new Promise((ok)=>{
        ajax({url:`/admin/${model_name}/list`, data:{'where[id][in]':ids,'order[field:id]':ids} }, (res)=>{
          ok(res.data.list);
          return false;
        })
      })
    },
    onsubmit(formData){
      let old_list_key = this.edit_row.model_name + ':' + this.edit_row.object_ids;
      let data = this.edit_row;
      s94Mjs.each(this.config, function (row){
        data[row.name] = row.value;
      })
      let list_key = data.model_name + ':' + data.object_ids;

      if (list_key !== old_list_key && data.object_ids){
        this.get_list(data.model_name, data.object_ids).then((list)=>{
          data.list = list;
          this.show_edit = false;
        })
      }else {
        if (!data.object_ids) data.list = [];
        this.show_edit = false;
      }
    },
    // 拖拽相关处理
    dragstart(row){
      if ('type' in row){
        this.drag_row = {
          title: '标题',
          type: row.type,
          config: '{}',
          model_name: '',
          object_ids: '',
          list: [],
          href: '',
          status: 1,
        }
      }else if('index' in row) {
        this.drag_row = this.card_list[row.index];
        this.drag_row.index = row.index;
      }else {
        this.drag_row = false;
      }
    },
    dragover(e){
      if (this.drag_row===false) return;
      let dom = s94(e.target).parents('.card_row')[0];
      if (dom){
        this.drop_index = Number(dom.getAttribute('index'));
        let h = dom.offsetHeight;
        let dh = s94Mjs.eventOffsetDom(dom, e).y;
        this.drop_dt_index = dh > h/2 ? 1 : 0;
      }else {
        this.drop_index = -1;
      }
    },
    drop(e){
      if (this.drop_index == -1) return this.dragend();
      let drag_row = this.drag_row;
      let drag_i = 'index' in drag_row ? drag_row.index : -1; // 拖拽的板块 index
      delete drag_row.index;
      let drop_i = this.drop_index + this.drop_dt_index; // 放下位置的板块 index

      this.card_list.splice(drop_i, 0, drag_row);

      if (drag_i == -1){
        this.to_edit(this.card_list[drop_i]);
      }else {
        if (drag_i > drop_i){
          this.card_list.splice(drag_i+1,1);
        }else {
          this.card_list.splice(drag_i,1);
        }
      }
      this.dragend();
    },
    dragend(e){
      this.drop_index = -1;
      this.drag_row = false;
    },
    copy(str){
      let input = this.$refs['input_copy'];
      input.value = str;
      input.select();
      document.execCommand("Copy");
      this.$message('复制文件地址成功！');
    },

    change_bottom_link(ids){
      if (!ids) return this.footer = [];
      this.get_list('link', ids).then((list)=>{
        this.footer = list;
      })
    }
  },
  watch: {
    'config.model_name.value'(v){
      this.config.object_ids.config = this.list_id_config_map[v] || '';
    },
    'config.type.value'(v){
      let config_map = {
        0:{style_type: {label:'轮播图类型',name:'style_type',type:'radio',config:['无边距','有边距'],tips:''}},
      }
      this.config.config.config = config_map[v] || '';
      if (this.config.config.config){
        this.config.config.type = 'json_param';
      }else {
        this.config.config.type = 'hidden';
        this.config.config.value = '{}';
      }
    },
  },
  mounted() {
    let app = this;
    if (!this.__iframe) window['app'] = this;

    ajax({url:'/admin/index_card/config',cache:true},function(res){
      app.card_list = res.data.card_list;
      app.footer = res.data.footer;

      s94Mjs.each(res.data.model_list, function (v){
        app.list_id_config_map[v.name] = 'model_base/index?model_name='+v.name+'&model_alias='+encodeURIComponent(v.alias);
      })
      let model_name_config = app.decode_config(res.data.model_list, {content_key:'alias', value_key:'name'});
      model_name_config.push({value:'agent', content:'代理商'})
      app.config.model_name.config = model_name_config;
      return false;
    })
  }
}
</script>
